package com.ckm.aop;

import com.ckm.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.concurrent.TimeUnit;

@Slf4j
@Aspect
@Component
@Order(1)
public class SessionAspect {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Before("@annotation(com.ckm.annotation.SessionInfo)")
    public void before(){
        HttpServletRequest request = (HttpServletRequest) RequestContextHolder.getRequestAttributes();
        assert request != null;
        String token = request.getHeader("token");
        if(token==null || token.isEmpty()){
            throw new BusinessException(250,"未登录");
        }
        if (Boolean.TRUE.equals(redisTemplate.hasKey(token))){
            log.info("更新token存活时间");
            redisTemplate.expire(token,30, TimeUnit.MINUTES);
        }else {
            throw new BusinessException(250,"登录过期");
        }
    }
}
